<?php
namespace control;
/*
*薪酬规则类
*/

class salaryRuleClass extends adIndexClass
{
    private const page = 'salaryRule';
    private const table = 'salary_rule';
    private const title = '薪酬规则';
    public array $ruleType = ['1' => '固定工资', '2' => '固定工资+绩效'];

    public function __construct()
    {
        parent::__construct();
        $this->ruleType = ['1' => L('salary.table.gu_ding_gong_zi'), '2' => L('salary.table.salary_per')];
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('salary.table.xin_chou_zu') => text(array("name" => "team")),
                    L('salary.table.lei_xing')     => select(array("name" => "type", "option" => $this->ruleType)),
                    L('salary.table.cjrq') => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ],
                [
                    L('salary.table.zhuang_tai') => select(["name" => "state", 'option' => ['启用', '停用']]),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('".self::page."','edit')\" class='spanButton'>" . L('salary.table.xin_zeng') . "</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">" . L('salary.table.shan_chu') . "</span>\n";
        }
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('{$this->get('cla')}','stateSwitch',{type:'启用'})\" class='spanButton'>" . L('topic.table.enable') . "</span>\n";
            $button .= "<span onclick=\"layer('{$this->get('cla')}','stateSwitch',{type:'停用'})\" class='spanButton'>" . L('topic.table.unenable') . "</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'team'      => [
                        'name'  => L('salary.table.xin_chou_zu'),
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'type' => [
                        'name'  => L('salary.table.lei_xing'),
                        'width' => 300,
                    ],
                    'people'  => [
                        'name'  => L('salary.table.ren_shu'),
                        'width' => 300,
                    ],
                    'time'         => [
                        'name'  => L('salary.table.cjrq'),
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => L('salary.table.zhuang_tai'),
                        'width' => 300,
                    ]
                ];
        }
        return $tr;
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "team" => $this->post('team'),//试卷编号
        );
        //全等查询数组
        $equal = array(
            "state" => $this->post('state'),//状态
            "type" => $this->post('type'),//类型
        );
        $and = "";
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'));
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => L('salary.table.salary_info'), "click" => "layer('" . self::page . "','edit',{id:'" . $array['id'] . "'})"),
                "detail" => array("title" => L('salary.table.salary_info'), "click" => "newIframe('" . L('salary.table.salary_info') . "','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "type":
                        $row[] = $this->ruleType[$array['type']];
                        break;
                    case "people":
                        $people = $array['member'] ? count(explode(',', $array['member'])) : 0;
                        $row[] = $people;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 120),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }


    /**
     * 编辑页
     * @return string
     */
    public function edit()
    {
        $id = $this->post('id') ?: self::getId();
        $info = query(self::table, " id = '" . $id . "' ");
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . L('salary.table.xin_chou_zu') . "：" => text(["name" => "team", 'class' => 'text', "value" => $info['team']]),
                    must . L('salary.table.lei_xing') . "：" => radio(["name" => "type", 'value' => $this->ruleType, "checked" => $info['type']]),
                ],
                [
                    L('salary.table.bei_zhu') . "：" => textarea(["name" => "text", 'class' => 'textarea', "value" => $info['text']]),
                ],
                [
                    must . L('salary.table.syry') . "：" => componentClass::staffSelector($info['selector'])
                ],
                [
                    must . L('salary.table.ji_ben_gong_zi') . "：" => text(["name" => "baseMoney", 'type' => 'number', 'unit' =>  static::$unit , 'class' => 'text', "value" => $info['baseMoney']]),
                    must . L('salary.table.gwgz') . "：" => text(["name" => "jobMoney", 'type' => 'number', 'unit' =>  static::$unit , 'class' => 'text', "value" => $info['jobMoney']]),
                ],
                [
                    must . L('salary.table.ji_xiao_gong_zi') . "：" => text(["name" => "performanceMoney", 'type' => 'number', 'unit' =>  static::$unit , 'class' => 'text performanceMoney', "value" => $info['performanceMoney']]),
                ],
                [
                    L('salary.table.tong_xun_bu_tie') . "：" => text(["name" => "telFee", 'unit' =>  static::$unit , 'type' => 'number', 'class' => 'text', "value" => $info['telFee']]),
                    L('salary.table.jtbt') . "：" => text(["name" => "trafficFee", 'unit' =>  static::$unit , 'type' => 'number', 'class' => 'text', "value" => $info['trafficFee']]),
                ],
                [
                    L('salary.table.glgz') . "：" => text(["name" => "workAgeFee", 'unit' =>  static::$unit , 'type' => 'number', 'class' => 'text', "value" => $info['workAgeFee']]),
                    L('salary.table.xue_li_jin_tie') . "：" => text(["name" => "educationFee", 'unit' =>  static::$unit , 'type' => 'number', 'class' => 'text', "value" => $info['educationFee']]),
                ],
                [
                    L('salary.table.gwgz') . "：" => text(["name" => "jobTitleFee", 'unit' =>  static::$unit , 'type' => 'number', 'class' => 'text', "value" => $info['jobTitleFee']]),
                    L('salary.table.gao_wen_bu_tie') . "：" => text(["name" => "temperatureFee", 'unit' =>  static::$unit , 'type' => 'number', 'class' => 'text', "value" => $info['temperatureFee']]),
                ],
                [
                    L('salary.table.jia_ban_bu_tie') . "：" => text(["name" => "overtimeFee", 'unit' =>  static::$unit , 'type' => 'number', 'class' => 'text', "value" => $info['overtimeFee']]),
                    L('salary.table.qi_ta_bu_tie') . "：" => text(["name" => "otherFee", 'unit' =>  static::$unit , 'type' => 'number', 'class' => 'text', "value" => $info['otherFee']]),
                ],
            ],
        ]);
        $html .= <<<efo
<script>
$(function (){
    setRadio();
})
$("[name='type']").click(function() {
   setRadio();
});
function setRadio(){
    let type = $("input[name='type']:checked").val();
    if(type==2){
         $(".performanceMoney").parent().parent().parent().css('display','flex');
    }else{
         $(".performanceMoney").parent().parent().parent().css('display','none');
    }
}
</script>
efo;
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 500, "html" => $html));
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $field = [
            'team' => $this->post('team'),
            'type' => $this->post('type'),
            'text' => $this->post('text'),
            'selector' => $this->post('staff')[0] ?? '',//员工选择器
            'baseMoney' => $this->post('baseMoney'),
            'jobMoney' => $this->post('jobMoney'),
            'telFee' => $this->post('telFee'),
            'trafficFee' => $this->post('trafficFee'),
            'workAgeFee' => $this->post('workAgeFee'),
            'educationFee' => $this->post('educationFee'),
            'jobTitleFee' => $this->post('jobTitleFee'),
            'temperatureFee' => $this->post('temperatureFee'),
            'overtimeFee' => $this->post('overtimeFee'),
            'otherFee' => $this->post('otherFee'),
        ];
        $staff = componentClass::returnStaffId($field['selector']);
        $field['member'] = implode(',', $staff);
        $annotation = [
            'team' => L('salary.table.xin_chou_zu'),
            'type' => L('salary.table.lei_xing'),
            'member' => L('salary.table.syry'),
            'baseMoney' => L('salary.table.ji_ben_gong_zi'),
            'jobMoney' => L('salary.table.gwgz'),
        ];

        $rules = [
            'team' => 'required',
            'type' => 'required',
            'member' => 'required',
            'baseMoney' => 'required|numeric',
            'jobMoney' => 'required|numeric',
        ];
        if ($field['type'] == 2) {
            //固定工资加绩效
            $field = array_merge($field, [
                'performanceMoney' => $this->post('performanceMoney'),
            ]);
            $annotation = array_merge($annotation, [
                'performanceMoney' => L('salary.table.ji_xiao_gong_zi'),
            ]);
            $rules = array_merge($rules, [
                'performanceMoney' => 'required|numeric',
            ]);
        }
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('salary.table.rule_edit_permission');
        } elseif (static::total(array('table' => self::table, 'where' => " and id !='$id' and team = '$field[team]'")) > 0) {
            $json['warn'] = L('salary.table.yczxtmcdxcz');
        } else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $userNo = codeTemplateClass::generateCode(self::page, [
                    'prefix' => 'XC',
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ], $field);
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $userNo,
                    'stid' => $this->control['stid'],
                    'state' => '启用',
                    'startTime' => $this->time,
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $text = str_replace(['{{staffName}}', '{{team}}', '{{id}}'], [$this->control['name'], $field['team'], $id], L('salary.table.rule_edit_text'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = L('salary.table.no_salary');
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );

            $button = [];
            if ($this->power(self::page, "edit")) {
                //按钮
                $button[] = [
                    "name" => L('salary.table.bian_ji'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "edit",
                    "post" => ["id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];

            }
            if ($this->power(self::page, "del")) {
                //按钮
                $button[] = [
                    "name" => L('salary.table.shan_chu'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                "详细信息" => array(
                    array(
                        L('salary.table.xin_chou_zu') => $info['team'],
                        L('salary.table.lei_xing') => $this->ruleType[$info['type']],
                        L('salary.table.syry') => componentClass::showSelector($info['selector']),
                    ),
                    array(
                        L('salary.table.bei_zhu') => pre($info['text']),
                    ),
                    array(
                        "基本工资（" . static::$unit ."）" => $info['baseMoney'],
                        "岗位工资(". static::$unit . ")" => $info['jobMoney'],
                        "绩效工资(". static::$unit . ")" => $info['performanceMoney'],
                        "通讯补贴基数（". static::$unit . "）" => $info['telFee'],
                    ),
                    array(
                        "交通补贴基数(". static::$unit . ")" => $info['trafficFee'],
                        "工龄工资(". static::$unit . ")" => $info['workAgeFee'],
                        "学历津贴（". static::$unit . "）" => $info['educationFee'],
                        "职称津贴(". static::$unit . ")" => $info['jobTitleFee'],
                    ),
                    array(
                        "高温补贴基数(". static::$unit . ")" => $info['temperatureFee'],
                        "加班补贴基数（". static::$unit . "）" => $info['overtimeFee'],
                        "其他补贴(". static::$unit . ")" => $info['otherFee'],
                    ),
                ),
                L('salary.table.xi_tong_xin_xi') => array(
                    array(
                        L('salary.table.xcgzbh') => $info['orderNo'],
                        L('salary.table.chuang_jian_ren') => self::findStaff($info['stid']),
                        L('salary.table.cjsj') => $info['time'],
                        L('salary.table.gxsj') => $info['updateTime'],
                    ),
                    array(
                        L('salary.table.sxsj') => self::null($info['startTime']),
                        L('salary.table.zhuang_tai') => $info['state'],
                    ),
                )
            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    /**
     * 启用/停用
     */
    public function stateSwitch()
    {
        $type = $this->post('type');
        $typeText = match ($type) {
            '启用' => L('topic.table.enable'),
            default => L('topic.table.unenable'),
        };
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                L('topic.table.tip') . "：" => L('topic.table.changeTip') . "：" . $typeText,
            ),
        ), 'hidden' => hidden(array('name' => 'type', 'value' => $type))));
        //返回
        return $this->layer(array("title" => L('salary.table.ztqh'), "height" => 165, "html" => $html, 'formTwo' => 'listForm'));
    }

    /**
     * 启用/停用
     */
    public function stateSwitchEdit()
    {
        $idArr = $this->post('listId');
        $type = $this->post('type');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('salary.table.rule_edit_permission');
        } elseif (empty($idArr) || !is_array($idArr)) {
            $json['warn'] = L('salary.table.qxzsj');
        } elseif (!in_array($type, ['启用', '停用'])) {
            $json['warn'] = L('salary.table.lei_xing_cuo_wu');
        } else {
            $field = [
                'state' => $type,
            ];
            $json['warn'] = update(array('table' => self::table, 'field' => $field, 'where' => " id in ('" . implode("','", $idArr) . "')"));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $operate = match ($type) {
                    '启用' => L('topic.table.enable'),
                    default => L('topic.table.unenable'),
                };
                $text = str_replace(['{{staffName}}', '{{state}}'], [$this->control['name'], $operate], L('salary.table.rule_enable_text')) . implode("','", $idArr);
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            }
        }
        //返回
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        switch ($act) {
            default:
                $act = 'del';
                $msg = L('salary.table.ruleDel');
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('jon.other.permission_warn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('salary.table.nmzscdzx');
        } elseif (empty($array)) {
            $json['warn'] = L('salary.table.nygsjdmzxzn');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] != '停用') {
                    $warn = L('salary.table.bstyztzbnsc');
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    //返回
                    $warn = L('salary.table.sccg');
                    $x++;
                }
                $text .= str_replace(['{{team}}', '{{id}}'], [$info['team'], $id], L('salary.table.rule_del_text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('salary.table.rule_del_log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('salary.table.rule_del_warn'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }
}
